//引入 axios 
import axios  from 'axios';
import env from '../config/env';
import iView from 'iview';
import Qs  from 'qs';

const getBaseURL = function(){
    if (env === 'development') { return 'http://api.tes.springrass.com/rest/' };
    if (env === 'test')  { return 'http://preapi.springrass.com/rest/' };
    if (env === 'production')  { return 'http://api.springrass.com/rest/' };
    return "http://localhost:8080";
}

let instance = axios.create({
    url: '/',
    method: 'get',
    baseURL: getBaseURL(), 　　　
    transformRequest: [function(data) {
        return Qs.stringify(data);
    }],
    transformResponse: [function(data) {
        return data;
    }],
    headers: {
        'Content-Type' : 'application/x-www-form-urlencoded'
    },
    paramsSerializer: function(params) {
        return Qs.stringify(params, { arrayFormat: 'brackets' })
    },
    timeout: 10000,
    responseType: 'json',
    validateStatus: function(status) {
        return status >= 200 && status < 300;
    },
    maxRedirects: 5
});

//添加请求拦截器，在请求时，显示 ElementUI 的加载组件
instance.interceptors.request.use(function(conf) {
    iView.LoadingBar.start()
    return conf;
}, function(error) {
    return Promise.reject(error);
});

// 添加响应拦截器 ，请求结束后，关闭 加载组件
instance.interceptors.response.use(function(response) {
    iView.LoadingBar.finish();
    return response;
}, function(error) {
    return Promise.reject(error);
});

const $axios = {
    get:function(url){
       return new Promise(function(resolve, reject) {
            instance.get(url).then((res) => {
                resolve(res);
            }).catch((error) => {
                reject(error);
            });
        });
    },
    post:function(){
        data = data || {};
        return new Promise(function(resolve, reject) {
            instance.post(url,data).then((response) => {
                resolve(response);
            }).catch((error) => {
                reject(error);
            });            
        });
    }    
}

export default function (Vue, options) {
    Vue.prototype.$axios = $axios;
};










